//
//  SendCodeView.swift
//  Box
//
//  Created by mn on 2025/3/31.
//

import UIKit
import SnapKit

class OTPTextField: UITextField {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    private func commonInit() {
        textAlignment = .center
        textColor = .white
        font = UIFont.systemFont(ofSize: 24, weight: .bold)
        keyboardType = .numberPad
        layer.borderWidth = 1
        layer.cornerRadius = 6
        backgroundColor = .white.withAlphaComponent(0.2)
        delegate = self
        
        addTarget(self, action: #selector(didBeginEditing), for: .editingDidBegin)
        addTarget(self, action: #selector(didEndEditing), for: .editingDidEnd)
    }
    
    @objc private func didBeginEditing() {
        layer.borderColor = UIColor.white.cgColor
    }

    @objc private func didEndEditing() {
        layer.borderColor = UIColor.clear.cgColor
    }
    
    override func deleteBackward() {
        if text?.isEmpty ?? true {
            (superview?.subviews.compactMap { $0 as? OTPTextField })?
                .first(where: { $0.isFirstResponder })?
                .resignFirstResponder()
        }
        super.deleteBackward()
    }
}

extension OTPTextField: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textField = textField as? OTPTextField else { return false }
        
        if string.isEmpty { return true }
        if let text = textField.text, !text.isEmpty { return false }
        
        textField.text = string
        DispatchQueue.main.async {
            textField.resignFirstResponder()
            if let nextField = textField.superview?.subviews.compactMap({ $0 as? OTPTextField }).first(where: { $0.text?.isEmpty ?? true }) {
                nextField.becomeFirstResponder()
            }
        }
        return false
    }
}

class SendCodeView: UIView {
    
    private let loginTipView = LoginTipView()
    private let codeStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 10
        stackView.distribution = .fillEqually
        return stackView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    func getInputCode() -> String? {
        let code = codeStackView.arrangedSubviews.compactMap { ($0 as? OTPTextField)?.text }.joined()
        return (code.count == 4 && code.allSatisfy { $0.isNumber }) ? code : nil
    }
    var phone: String? = nil{
        didSet{
            guard let phone  else { return }
            let text = "请输入发送至 \(phone) 的验证码"
            let attributedString = NSMutableAttributedString(string: text)
            if let linkRange = text.range(of: phone) {
                let nsRange = NSRange(linkRange, in: text)
                attributedString.addAttribute(.foregroundColor, value: UIColor(hex: "#CAFE67"), range: nsRange)
            }
            loginTipView.tipLabel.attributedText = attributedString
        }
    }
    private func setupView() {
        addSubview(loginTipView)
        addSubview(codeStackView)

        loginTipView.textLabel.text = "验证码已发送"

        loginTipView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
        }

        // 添加验证码输入框
        for _ in 0..<4 {
            let textField = OTPTextField()
            textField.snp.makeConstraints { make in
                make.width.equalTo(46)
                make.height.equalTo(52)
            }
            codeStackView.addArrangedSubview(textField)
        }
        
        codeStackView.snp.makeConstraints { make in
            make.top.equalTo(loginTipView.snp.bottom).offset(48)
            make.centerX.equalToSuperview()
        }
    }
}
